package com.zgkxzx.java.mutilThread.forkAndJoin;

import java.util.concurrent.ExecutionException;
import java.util.concurrent.RecursiveTask;

/**
 * 创建者 zgkxzx
 * 日期   1/3/18
 * 描述
 */

public class ProductJoinTask extends RecursiveTask<Integer> {
    private int start;
    private int end;

    public ProductJoinTask(int start, int end) {
        this.start = start;
        this.end = end;
    }


    @Override
    protected Integer compute() {
        if (end - start < 100) {
            int sum = 0;
            for (int i = start; i <= end; i++) {
                sum += i;
            }
            return sum;
        } else {
            int sum = 0;
            int middle = (start + end) / 2;
            ProductJoinTask productJoinTask = new ProductJoinTask(start, middle + 1);
            ProductJoinTask productJoinTask2 = new ProductJoinTask(middle + 1, end);

            invokeAll(productJoinTask, productJoinTask2);

            try {
                sum = productJoinTask.get() + productJoinTask2.get();
            } catch (InterruptedException e) {
                e.printStackTrace();
            } catch (ExecutionException e) {
                e.printStackTrace();
            }

            return sum;
        }


    }
}
